package bll

import (
	"context"
	"maya-service/store/mysql"

	"maya-service/model"
	"maya-service/model/entity"
	"maya-service/model/mapping"
	"maya-service/store"
	"time"
)

type dictionaryItem struct {
	iDictionaryItem store.IDictionaryItem
}

var DictionaryItem = &dictionaryItem{
	iDictionaryItem: mysql.DictionaryItem,
}

func init() {
	Register(DictionaryItem)
}

func (a *dictionaryItem) init() func() {
	return func() {}
}

// Create
func (a *dictionaryItem) Create(ctx context.Context, in *model.DictionaryItemCreateRequest) error {
	var (
		err error
	)
	c := buildDictionaryItem(in)
	_, err = a.iDictionaryItem.Create(ctx, c)
	return err
}

// Update
func (a *dictionaryItem) Update(ctx context.Context, in *model.DictionaryItemUpdateRequest) error {
	var (
		dict = make(map[string]interface{})
	)

	if in.Code != nil {
		dict["code"] = in.Code
	}

	if in.Key != nil {
		dict["key"] = in.Key
	}

	if in.Value != nil {
		dict["value"] = in.Value
	}

	if in.Status != nil {
		dict["status"] = in.Status
	}

	if in.SortOrder != nil {
		dict["sort_order"] = in.SortOrder
	}

	if in.Description != nil {
		dict["description"] = in.Description
	}

	if in.CreatedAt != nil {
		dict["created_at"] = in.CreatedAt
	}

	if in.UpdatedAt != nil {
		dict["updated_at"] = in.UpdatedAt
	}

	// do other update here
	updateAt := time.Now().Unix()
	in.UpdatedAt = &updateAt
	return a.iDictionaryItem.Update(ctx, in.Id, dict)
}

// Delete
func (a *dictionaryItem) Delete(ctx context.Context, in *model.DictionaryItemDeleteRequest) error {
	return a.iDictionaryItem.Delete(ctx, in.Id)
}

// List
func (a *dictionaryItem) List(ctx context.Context, in *model.DictionaryItemListRequest) (*model.DictionaryItemListResponse, error) {
	var (
		err   error
		total int
		list  []*entity.DictionaryItem
		out   = &model.DictionaryItemListResponse{}
	)

	if total, list, err = a.iDictionaryItem.List(ctx, in); err != nil {
		return nil, err
	}

	out.Total = total
	out.List = mapping.DictionaryItemsEntityToDto(list)

	return out, nil
}

// Find
func (a *dictionaryItem) Find(ctx context.Context, in *model.DictionaryItemInfoRequest) (*model.DictionaryItemInfo, error) {
	var (
		err  error
		data *entity.DictionaryItem
		out  = &model.DictionaryItemInfo{}
	)

	if data, err = a.iDictionaryItem.Find(ctx, in); err != nil {
		return nil, err
	}

	out = mapping.DictionaryItemEntityToDto(data)
	return out, nil
}

// buildDictionaryItem build entity
func buildDictionaryItem(in *model.DictionaryItemCreateRequest) *entity.DictionaryItem {

	ety := &entity.DictionaryItem{}

	ety.Code = in.Code

	ety.Key = in.Key

	ety.Value = in.Value

	ety.Status = in.Status

	ety.SortOrder = in.SortOrder

	ety.Description = in.Description

	ety.CreatedAt = time.Now().Unix()

	ety.UpdatedAt = time.Now().Unix()

	return ety
}
